<?php

namespace app\api\controller;

use app\facade\Redis;
use app\models\{User as Users, Address, IntergralLog, IntergralBanner, IntergralCate, IntergralGoods, IntergralOrder, IntergralOrdergoods, Region};
use think\Validate;
use think\Db;

class Goods extends Base
{
    public function banner()
    {
        $list = (new IntergralBanner())->field('id,created', true)->select();
        $this->result($list, 0, '获取成功');
    }

    public function cate()
    {
        $list = (new IntergralCate())->where('isshow', 1)->order('orders desc')->field('isshow,created,orders', true)->select();
        $this->result($list, 0, '获取成功');
    }

    public function categoods()
    {
        $cate = $this->request->get('cate/d', 0);
        $ishot = $this->request->get('ishot/d', 0);
        $list = (new IntergralGoods())->where('puton', 1);
        if ($cate) {
            $list = $list->where('cateid', $cate);
        }
        if ($ishot) {
            $list = $list->where('ishot', $ishot);
        }
        $list = $list->order(['ishot desc'])->field('isshow,created,detail,puton,cateid', true)
            ->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($list as $lists) {
            $lists['images'] = json_decode($lists['images'], true);
        }
        $this->result($list, 0, '获取成功');
    }


    public function goodsdetail()
    {
        $id = $this->request->get('id/d', 0);
        $list = (new IntergralGoods())->where('id', $id)->field('isshow,created,puton,cateid', true)->find();
        if (!empty($list)) {
            $list['images'] = json_decode($list['images'], true);
            $list['detail'] = json_decode($list['detail'], true);
        }
        $this->result($list, 0, '获取成功');
    }

    public function add_order()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'addressid' => 'require',
            'goodsid' => 'require',
            'num' => 'require|gt:0|number'
        ], [
            'addressid.require' => '地址id不能为空',
            'goodsid.require' => '商品id不能为空',
            'num.require' => '商品数量不能为空',
            'num.gt' => '商品数量必须大于0',
            'num.number' => '商品数量必须是整数',

        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        //判断收货地址是否存在
        $address = (new Address())->where(['user_id' => $this->request->user_id, 'id' => $data['addressid']])->find();
        if (empty($address)) {
            $this->result([], 1, '地址信息不存在');
        }
        $good = (new IntergralGoods())->where('id', $data['goodsid'])->where('puton', 1)->find();
        if (empty($good)) {
            $this->result([], 1, '商品已下架');
        }
        if ($good['sku'] < $data['num']) {
            $this->result([], 1, '商品库存不足');
        }
        $total = $data['num'] * $good['intergral'];
        $user = (new Users())->where(['id' => $this->request->user_id])->find();
        if ($user['integral'] < $total) {
            $this->result([], 1, '积分不足');
        }
        Db::startTrans();
        try {
            (new IntergralGoods())->where('id', $data['goodsid'])->setDec('sku', $data['num']);
            $id = (new IntergralOrder())->insertGetId([
                'user_id' => $this->request->user_id,
                'name' => $address['name'],
                'mobile' => $address['mobile'],
                'province' => $address['province'],
                'area' => $address['area'],
                'city' => $address['city'],
                'street' =>  $address['street'],
                'address' =>  $address['address'],
                'lon' => $address['lon'],
                'lat' =>  $address['lat'],
                'status' => 1,
                'total' => $total,
                'info' => !empty($data['info']) ? $data['info'] : '',
                'dates' => date('Y-m-d')
            ]);
            (new IntergralOrdergoods())->insert([
                'orderid' => $id,
                'goodsid' => $data['goodsid'],
                'num' => $data['num'],
                'title' => $good['title'],
                'shortitle' => $good['shortitle'],
                'price' => $good['price'],
                'intergral' => $good['intergral'],
                'images' => $good['images']
            ]);
            if ($total > 0) {
                (new Users())->IntergralEdit($user['id'], $user['integral'], -$total, 2, $id, '兑换商品');
            }
            Db::commit();
        } catch (\Exception $e) {
            dump($e->getMessage());
            Db::rollback();
            $this->result([], 1, '操作失败');
        }
        $this->result([], 0, '操作成功');
    }


    public function order()
    {
        $list = (new IntergralOrder())->order('id desc');
        $status = $this->request->get('status/d', 0);
        if (!empty($status)) {
            $list = $list->where('status', $status);
        }
        $list = $list->field('id,status,created,total')->where('user_id', $this->request->user_id)->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($list as $lists) {
            $lists['goodslist'] = (new IntergralOrdergoods())->field('title,images,num,intergral')->where('orderid', $lists['id'])->select();
            foreach ($lists['goodslist'] as $goods) {
                $goods['images'] = json_decode($goods['images'], true);
            }
            if ($lists['status'] == 1) {
                $lists['status_text'] = '待发货';
            }
            if ($lists['status'] == 2) {
                $lists['status_text'] = '待确认';
            }
            if ($lists['status'] == 3) {
                $lists['status_text'] = '已完成';
            }
            if ($lists['status'] == 4) {
                $lists['status_text'] = '已取消';
            }
        }
        $this->result($list, 0, '获取成功');
    }

    public function orderdetail()
    {
        $id = $this->request->get('id/d', 0);
        $lists = (new IntergralOrder())->where('id', $id)->field('id,status,created,total,province,city,area,street,info,postalname,postalcode,address')
            ->where('user_id', $this->request->user_id)->find();
        if (!empty($lists)) {
            $lists['province_text'] = (new Region())->where(['area_code' => $lists['province']])->value('name');
            $lists['city_text'] = (new Region())->where(['area_code' => $lists['city']])->value('name');
            $lists['area_text'] = (new Region())->where(['area_code' => $lists['area']])->value('name');
            $lists['street_text'] = (new Region())->where(['id' => $lists['street']])->value('name');
            $lists['goodslist'] = (new IntergralOrdergoods())->field('title,images,num,intergral')->where('orderid', $lists['id'])->select();
            foreach ($lists['goodslist'] as $goods) {
                $goods['images'] = json_decode($goods['images'], true);
            }
            $lists['ordersn'] = $lists['id'] + pow(21, 8);
            if ($lists['status'] == 1) {
                $lists['status_text'] = '待发货';
            }
            if ($lists['status'] == 2) {
                $lists['status_text'] = '待确认';
            }
            if ($lists['status'] == 3) {
                $lists['status_text'] = '已完成';
            }
            if ($lists['status'] == 4) {
                $lists['status_text'] = '已取消';
            }
        }
        $this->result($lists, 0, '获取成功');
    }

    public function cacelconfirm()
    {
        $data = $this->request->get();
        $validate = new Validate([
            'id' => 'require',
            'status' => 'require|in:1,2'
        ], [
            'id.require' => '订单id不能为空',
            'status.require' => '修改状态不能为空',
            'status.in' => '修改类型不正确',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $order = (new IntergralOrder())->where(['id' => $data['id'], 'user_id' => $this->request->user_id])->find();
        if (empty($order)) {
            $this->result([], 1, '订单不存在');
        }
        if ($data['status'] == 1 && $order['status'] != 1) {
            $this->result([], 1, '订单不可取消');
        }
        if ($data['status'] == 2 && $order['status'] != 2) {
            $this->result([], 1, '订单不可完成');
        }
        if ($data['status'] == 1) {
            $status = 4;
        } else {
            $status = 3;
        }
        $user = (new Users())->where('id', $this->request->user_id)->find();
        Db::startTrans();
        try {
            (new IntergralOrder())->where(['id' => $data['id'], 'status' => $order['status']])->update(['status' => $status]);
            if ($data['status'] == 1 && $order['total'] > 0) {
                (new Users())->IntergralEdit($user['id'], $user['integral'], $order['total'], 3, $order['id'], '兑换商品取消');
            }
            Db::commit();
        } catch (\Exception $e) {
            dump($e->getMessage());
            Db::rollback();
            $this->result([], 1, '操作失败');
        }
        $this->result([], 0, '操作成功');
    }
}
